/*
 * Copyright 2007 - The JDPF Project Team (http://www.jdpf.org) 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
package org.jdpf.plugins.datatypes.basic;

import javax.measure.Measure;

import org.jdpf.core.plugins.datatypes.AbstractDataType;
import org.jdpf.core.plugins.exceptions.PluginException;
import org.jdpf.core.plugins.exceptions.PluginExceptionsEnum;

public class MeasureTextAdapter extends AbstractDataType {

	private Measure measure;
	private String label; 

	public MeasureTextAdapter(Measure measure) {
		this.measure = measure;
	}
	
	public MeasureTextAdapter(String label) {
		this.label = label;
	}
	
	public Measure getMeasure() {
		return measure;
	}

	public void setMeasure(Measure measure) {
		this.measure = measure;
	}

	@Override
	public Object getValue() {
		return (measure!=null)?measure:label;
	}
	
	public String getStringValue() throws PluginException { // TODO exception handling 
		if(measure != null) {
			if(measure.getValue() instanceof Integer) {
				return Integer.toString(measure.intValue(measure.getUnit()));
			} else if(measure.getValue() instanceof Long) {
				return Long.toString(measure.longValue(measure.getUnit()));
			} else if(measure.getValue() instanceof Float) {
				return Float.toString(measure.floatValue(measure.getUnit()));
			} else if(measure.getValue() instanceof Double) {
				return Double.toString(measure.doubleValue(measure.getUnit()));
			}
		} else if(label != null) {
			return label;
		} 

		throw new PluginException(PluginExceptionsEnum.InputTypeNotRecognized, this.getClass().getName(), "Type '" + measure.getValue().getClass().getName() + "' not recognized.");
	}
	
	
	public MeasurePrecision getPrecision() {
		if(measure.getValue() instanceof Integer) {
			return MeasurePrecision.INT;
		} else if(measure.getValue() instanceof Long) {
			return MeasurePrecision.LONG;
		} else if(measure.getValue() instanceof Float) {
			return MeasurePrecision.FLOAT;
		} else if(measure.getValue() instanceof Double) {
			return MeasurePrecision.DOUBLE;
		} else if(measure == null && label != null) {
			return MeasurePrecision.STRING;
		} 
		else return MeasurePrecision.INT; // TODO exception
	}
}
